<template>
  <el-form
    class="task-form"
    :model="form"
    ref="formRef"
    :rules="rules"
    label-width="auto"
  >
    <!-- 作业标题 -->
    <el-form-item label="作业标题：" required prop="title">
      <el-input
        v-model="form.title"
        maxlength="64"
        minlength="2"
        placeholder="请输入2-64个中、英文字符或数字"
      />
    </el-form-item>
    <!-- 发布时间 截止时间 -->
    <div class="flex-between">
      <el-form-item
        label="发布时间："
        prop="publishTime"
        class="task-form-item"
      >
        <el-date-picker
          :disabled-date="commonDateDisable"
          v-model="form.publishTime"
          type="datetime"
          format="YYYY-MM-DD HH:mm"
          placeholder="立即发布"
          popper-class="my-date-picker"
        />
      </el-form-item>
      <el-form-item
        label="截止时间："
        required
        prop="endTime"
        class="task-form-item"
      >
        <el-date-picker
          v-model="form.endTime"
          :disabled-date="commonDateDisable"
          type="datetime"
          placeholder="请选择截止时间"
          format="YYYY-MM-DD HH:mm"
          popper-class="my-date-picker"
        />
      </el-form-item>
    </div>
    <el-form-item label="作业描述：">
      <el-input
        type="textarea"
        :rows="6"
        v-model="form.desc"
        placeholder="请输入作业描述"
        :maxlength="100"
      />
    </el-form-item>
    <el-form-item label="上传附件：" v-if="props.taskType !== 3">
      <el-upload
        style="width: 100%"
        :auto-upload="false"
        :on-change="customUpload"
        :show-file-list="false"
        accept=".xls,.xlsx,.pdf,.txt,.ppt,.pptx,.doc,.docx"
      >
        <el-button style="margin-top: 0.04rem" link type="primary">
          点击上传附件
        </el-button>
      </el-upload>
      <div class="flex file-box">
        <div class="file-item" v-for="(file, index) in form.file" :key="index">
          <img
            src="@/assets/images/assignment/delete.png"
            @click="onDeleteFile(index)"
            class="hover close-img"
            alt=""
          />
          <img class="file-img" :src="getFileImg(file.name)" />
        </div>
      </div>
    </el-form-item>

    <el-form-item
      v-if="props.taskType !== 3"
      label="错题重练："
      class="wrong-return flex-between"
      prop="wrongReturn"
    >
      <el-switch v-model="form.wrongReturn" />
    </el-form-item>
    <el-form-item label="答案公布：" prop="answerTime">
      <el-date-picker
        :disabled-date="answerTimeDis"
        v-model="form.answerTime"
        type="datetime"
        format="YYYY-MM-DD HH:mm"
        placeholder="提交后可见"
        popper-class="my-date-picker"
      />
    </el-form-item>
    <div class="flex return-box" v-if="form.wrongReturn">
      <el-form-item
        label="重练时间"
        required
        prop="returnTime"
        label-position="top"
        format="YYYY-MM-DD HH:mm"
        class="task-small-item"
      >
        <el-date-picker
          :disabled-date="disabledDate"
          v-model="form.returnTime"
          type="datetime"
          format="YYYY-MM-DD HH:mm"
          style="width: 1.2rem"
          placeholder="请选择重练时间"
          popper-class="my-date-picker"
        />
      </el-form-item>
      <el-form-item
        label="重练题型"
        required
        prop="returnQuesType"
        label-position="top"
        class="task-small-item"
      >
        <el-select
          v-model="form.returnQuesType"
          placeholder="请选择重练题型"
          style="width: 1.2rem"
        >
          <el-option
            v-for="item in returnQUesTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
    </div>
  </el-form>
</template>

<script setup>
import { ref } from 'vue'
import { useAuthStore } from '@/stores'
import { storeToRefs } from 'pinia'
import dayjs from 'dayjs'
import { uploadFile, getFileImg, beforeUpload } from '@/utils/upload'
import { ElMessage, ElLoading } from 'element-plus'
import { useRoute } from 'vue-router'
import {
  returnQUesTypeOptions,
  commonDateDisable
} from '@/views/assignment/util'

const props = defineProps({
  taskType: {
    type: Number // 1-课程 2-习题 4-错题 3-举一反三
  },
  course: {
    type: Object,
    default: () => {
      return { course_id: null, course_name: '', subjectId: 0 }
    }
  }
})

const route = useRoute()
const authStore = useAuthStore()
const { userInfo } = storeToRefs(authStore)
const formRef = ref()

const getTitle = () => {
  let text = ''
  switch (props.taskType) {
    case 1:
      text = `${props.course.course_name}课程任务`
      break
    case 2:
      text = `${dayjs().format('YYYY-MM-DD')}习题任务`
      break
    case 3:
      text = `${dayjs().format('YYYY-MM-DD')}举一反三任务`
      break
  }
  return text
}

const form = ref({
  title: getTitle(),
  publishTime: null,
  endTime: dayjs().add(3, 'day').endOf('day'),
  desc: '',
  file: [],
  wrongReturn: false,
  returnType: 1, // 重练方式
  returnTime: dayjs().add(4, 'day').set('hour', 7).set('minute', 0), // 重练时间
  returnQuesType: 0, // 重练题型
  answerTime: null
})

const rules = ref({
  publishTime: [
    {
      validator: (_, value, callback) => {
        if (dayjs(value).unix() <= dayjs().unix()) {
          callback(new Error('发布时间应大于当前时间'))
        } else if (
          form.value.endTime &&
          dayjs(value).unix() >= dayjs(form.value.endTime).unix()
        ) {
          callback(new Error('发布时间应小于发布时间'))
        }
        callback()
      },
      trigger: 'change'
    }
  ],
  endTime: [
    {
      required: true,
      validator: (_, value, callback) => {
        if (!value) {
          callback(new Error('请选择截止时间'))
          return
        }

        if (dayjs(value).unix() <= dayjs().unix()) {
          callback(new Error('截止时间应大于当前时间'))
          return
        }
        if (form.value.answerTime) {
          formRef.value.validateField('answerTime')
        }
        if (form.value.wrongReturn) {
          formRef.value.validateField('returnTime')
        }
        callback()
      },
      trigger: 'change'
    }
  ],

  returnTime: [
    {
      required: true,
      validator: (_, value, callback) => {
        if (
          form.value.endTime &&
          dayjs(value).unix() <= dayjs(form.value.endTime).unix()
        ) {
          callback(new Error('重练时间应在截止时间之后'))
        }
        callback()
      },
      trigger: 'change'
    }
  ],
  title: [
    {
      required: true,
      validator: (_, value, callback) => {
        if (value.length < 2 || value.length > 64) {
          callback(new Error('请输入2-64个中、英文字符或数字'))
        }
        callback()
      },
      trigger: 'change'
    }
  ],
  answerTime: [
    {
      validator: (_, value, callback) => {
        let time = dayjs(value).unix()
        if (
          value &&
          (time <= dayjs(form.value.publishTime || Date.now()).unix() ||
            time >= dayjs(form.value.endTime).unix())
        ) {
          callback(new Error('请设置在发布时间和截止时间之间'))
        }
        callback()
      },
      trigger: 'change'
    }
  ]
})

const answerTimeDis = time => {
  let startTime = form.value.publishTime
    ? dayjs(form.value.publishTime).startOf('day')
    : dayjs().startOf('day')

  return (
    time.getTime() < dayjs(startTime).valueOf() ||
    time.getTime() > dayjs(form.value.endTime).valueOf()
  )
}

// 上传文件
const customUpload = async file => {
  let isContinue = beforeUpload(file)
  if (!isContinue) {
    return
  }
  if (form.value.file.length > 3) {
    ElMessage.info('已达到上传上限')
    return
  }
  let name = file.name
  name = name.slice(0, name.lastIndexOf('.'))
  let reg =
    /[`~!@#$%^&*()_\-+=<>?:"{}|,.\\/;'\\[\]·！#￥（——）：；“”‘、，|《。》？、【】[\]]/im
  if (reg.test(name)) {
    ElMessage.error(`文件名不能包含+ ?><\\/*|": 等特殊字符，请修改后重新上传`)
    return
  }
  const loading = ElLoading.service({
    lock: true,
    text: '加载中...',
    background: 'rgba(0, 0, 0, 0.3)'
  })
  const res = await uploadFile(file)
  loading.close()
  form.value.file.push(res)
}

const onDeleteFile = index => {
  form.value.file.splice(index, 1)
}

const disabledDate = time => {
  return time.getTime() <= dayjs(form.value.endTime).add(-1, 'day').valueOf()
}

// 检查表单数据
const validateForm = async ruleForm => {
  return await ruleForm.validate(valid => {
    if (valid) {
      return true
    } else {
      return false
    }
  })
}

// 提交表单
const getForm = async () => {
  if (!(await validateForm(formRef.value))) return null

  const param = {
    homework_title: form.value.title,
    homework_description: form.value.desc,
    task_type: props.taskType,
    create_time: form.value.publishTime
      ? dayjs(form.value.publishTime).unix()
      : dayjs().unix(),
    deadline: dayjs(form.value.endTime).unix(),
    annex: form.value.file.map(item => ({
      url: item.url,
      name: item.name
    })),
    teacher_id: Number(userInfo.value.userId),
    teacher_name: userInfo.value.userName,
    school_id: Number(userInfo.value.school_id),
    task_classification: route.path.includes('target-boost') ? 2 : 1,
    wrong_question: {
      tag: Number(form.value.wrongReturn)
    },
    answer_check_time: form.value.answerTime
      ? dayjs(form.value.answerTime).unix()
      : null
  }
  // 开启错题处理
  if (param.wrong_question.tag) {
    param.wrong_question = {
      ...param.wrong_question,
      retrain_time: dayjs(form.value.returnTime).unix(),
      train_method: form.value.returnType,
      wrong_question_type: form.value.returnQuesType
    }
  }
  return param
}

// 编辑任务初始化表单
const initForm = task_info => {
  const { wrong_question } = task_info
  form.value = {
    title: task_info.homework_title,
    publishTime: task_info.create_time * 1000,
    endTime: task_info.deadline * 1000,
    desc: task_info.homework_description,
    file: task_info.annex || [],
    wrongReturn: wrong_question.tag === 1,
    answerTime: task_info.answer_check_time
      ? task_info.answer_check_time * 1000
      : null
  }
  if (form.value.wrongReturn) {
    form.value.returnQuesType = wrong_question.wrong_question_type
    form.value.returnTime = wrong_question.retrain_time * 1000
    form.value.returnType = wrong_question.train_method
  }
}
defineExpose({
  getForm,
  initForm
})
</script>

<style lang="less" scoped>
.task-form {
  max-width: 100%;

  /* stylelint-disable ebag/selector-class-pattern */
  :deep(.el-form-item__label, .el-checkbox) {
    height: 40px;
    line-height: 40px;
  }
  .task-form-item {
    width: 48% !important;
  }
  .task-small-item {
    width: 30% !important;
  }
  .file-box {
    flex-wrap: wrap;
    gap: 20px;

    .file-item {
      position: relative;
      width: 44px;
      height: 44px;
      margin-top: 10px;

      .close-img {
        position: absolute;
        right: 0;
        top: 0;
        width: 14px;
        height: 14px;
        transform: translate(50%, -50%);
        display: none;
      }

      &:hover {
        .close-img {
          display: block;
        }
      }

      .file-img {
        width: 44px;
        height: 44px;
      }
    }
  }

  .return-box {
    gap: 20px;
    margin-bottom: 10px;
  }

  /* stylelint-disable ebag/selector-class-pattern */
  :deep(.el-form-item) {
    font-size: @size-base !important;
    .el-form-item__label {
      font-size: @size-base !important;
      padding-right: 4px;
    }
    .el-input__inner {
      font-size: @size-base !important;
    }
    .el-button {
      font-size: @size-base !important;
    }
    .el-textarea__inner {
      font-size: @size-base !important;
    }
    .el-form-item__label,
    .el-checkbox {
      height: 40px;
      line-height: 40px;
    }
  }

  .setting-icon {
    margin-left: 20px;
    font-size: 20px;
  }
  .wrong-return {
    :deep(.el-form-item__content) {
      flex: unset;
    }
  }
}
</style>

<!-- eslint-disable -->
<style lang="less">
.my-date-picker {
  .el-date-table {
    font-size: @base-size;
  }
  .el-input--small {
    height: 30px;
    font-size: @base-size;
  }
  .is-text {
    display: none;
  }
}
</style>
